<template>
  <div>
    <el-row :gutter="20">
      <!--角色数据-->
      <el-col :span="20" :xs="24">
        <el-form :model="queryParams" ref="queryForm" :inline="true"  label-width="68px">
          <el-form-item label="角色名称" prop="name">
            <el-input
              v-model="queryParams.name"
              placeholder="模糊查询"
              clearable
              size="small"
              style="width: 240px"
              @keyup.enter.native="selectRole"
            />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select
              v-model="queryParams.status"
              placeholder="角色状态"
              clearable
              size="small"
              style="width: 240px"
            >
            <el-option
                v-for="dict in statusOptions"
                :key="dict.id"
                :label="dict.format"
                :value="dict.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="selectRole">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

      
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="clickAdd"
            >新增</el-button>
          </el-col>
        </el-row>
        <el-table v-loading="loading" :data="roleList">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="角色编号" align="center" key="id" prop="id"  />
          <el-table-column label="角色名称" align="center" key="name" prop="name"/>
          <el-table-column label="状态" align="center" key="status">
            <template slot-scope="scope" v-if="scope.row.id >3 ">
              <el-switch
                v-model="scope.row.status"
                active-value="0"
                inactive-value="1"
                @change="statusChange(scope.row)"
              ></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" align="center" prop="createTime" v-if="columns[3].visible" width="160">
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            width="320"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope" >
              <el-button v-if="scope.row.id >3"
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
              >修改</el-button>
              <el-button v-if="scope.row.id >3"
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
              >删除</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-notebook-2"
                @click="handleMenu(scope.row)"
              >菜单</el-button>
              <el-button 
                size="mini"
                type="text"
                icon="el-icon-user-solid"
                @click="handleSelect(scope.row)"
              >用户</el-button>
            </template>
          </el-table-column>
        </el-table>
        

        <pagination
          v-show="this.sum>0"
          :total="this.sum"
          :page.sync='queryParams.page'
          :limit.sync='queryParams.number'
          @pagination="selectRole"
        />
      </el-col>
    </el-row>

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="角色昵称" prop="name">
              <el-input v-model="form.name" placeholder="请输入角色昵称" maxlength="30" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="角色状态">
              <el-select v-model="form.status" placeholder="请选择">
                <el-option
                  v-for="dict in statusOptions"
                  :key="dict.id"
                  :label="dict.format"
                  :value="dict.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="title" :visible.sync="openMenu" width="1000px" append-to-body>
      <el-table
      v-if="refreshTable"
      ref="menuRef"
      highlight-current-row
      v-loading="loadingMenu"
      :data="menuList"
      row-key="id"
      :default-expand-all="true"
      @select="rowSelect"
    	@select-all="selectAll"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column type="selection"  width="50" align="center" />
      <el-table-column prop="name" label="菜单名称" width="260"></el-table-column>
      <el-table-column prop="imgUrl" label="图标" align="center" width="100">
        <template slot-scope="scope">
          <i :class="scope.row.imgUrl" />
        </template>
      </el-table-column>
      <el-table-column prop="appUrl" label="组件路径" :show-overflow-tooltip="true"></el-table-column>
      <el-table-column prop="id" label="菜单编号" width="100"></el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="200">
      </el-table-column>
    </el-table>
    <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="toUpdate">确 定</el-button>
        <el-button @click="cancelMenu">取 消</el-button>
    </div>
    </el-dialog>

    <el-dialog :title="title" :visible.sync="openUser" width="1100px" append-to-body>
          <el-form :model="queryUser" ref="queryFormUser" :inline="true"  label-width="68px">
            <el-form-item label="用户名称" prop="userName">
              <el-input
                v-model="queryUser.userName"
                placeholder="模糊查询"
                clearable
                size="small"
                style="width: 240px"
                @keyup.enter.native="selectUser"
              />
            </el-form-item>
            <el-form-item label="性别" prop="sex">
              <el-select
                v-model="queryUser.sex"
                placeholder="性别"
                clearable
                size="small"
                style="width: 240px"
              >
              <el-option
                  v-for="dict in sexOptions"
                  :key="dict.id"
                  :label="dict.format"
                  :value="dict.id"
                />
              </el-select>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="selectUser">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQueryUser">重置</el-button>
            </el-form-item>
            <el-row :gutter="10" class="mb8">
        </el-row>
          </el-form>
           <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-view"
              size="mini"
              @click="switchUser"
            >{{userButtonTilet1}}</el-button>
          </el-col>
          <el-table v-loading="loading" :data="userList">
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column label="用户编号" align="center" key="id" prop="id"  />
            <el-table-column label="用户名称" align="center" key="name" prop="name" />
            <el-table-column label="登录账号" align="center" key="account" prop="account"  />
            <el-table-column label="部门名称" align="center" key="depId" prop="depId"  />
            <el-table-column label="性别" align="center" key="sex" prop="sex"  />
            <el-table-column label="状态" align="center" key="status" prop="status"  />
            <el-table-column label="创建时间" align="center" prop="createTime" width="160">
            </el-table-column>
            <el-table-column
            label="操作"
            align="center"
            width="160"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleCancel(scope.row)"
              >{{userButtonTilet2}}</el-button>
            </template>
          </el-table-column>
          </el-table>
          

          <pagination
            v-show="this.sumUser>0"
            :total="this.sumUser"
            :page.sync='queryUser.page'
            :limit.sync='queryUser.number'
            @pagination="selectUser"
          />
    </el-dialog>

  </div>
</template>

<script>
import {getStatusApi,getSexApi} from "@/api/system/common"
import {selectRoleApi,selectRoleMenuApi,selectUserRoleApi,updateRoleStatusApi,deleteRoleApi,cancelRoleUserApi,updateRoleMenuApi,updateRoleApi,addRoleApi} from "@/api/system/role"
export default {
  name: "user",
  // components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      loadingMenu: true,
      loadingUser: true,
      refreshTable: true,
      menuList: [],
      // 用户表格数据
      userList: [],
       // 是否显示弹出层
      openMenu: false,
      // 导出遮罩层
      exportLoading: false,
      // 角色表格数据
      roleList: null,
      isSelectMenu: true,
      sum: 0,
      sumUser: 0,
      userButtonTilet1: '未授权', 
      userButtonTilet2: '取消授权',
      userButtonTilet3: '全部取消',  
       // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openUser: false,
      // 状态数据
      statusOptions: [],
      sexOptions:[],
      form: {},
      roleId: undefined,
      queryUser:{
        page: 1,
        number: 10,
        userType: 0,
        id: undefined,
        userName: undefined,
        depName: undefined,
        mobile: undefined,
        status: undefined,
        sex: undefined
      },
      // 查询参数
      queryParams: {
        page: 1,
        number: 10,
        name: undefined,
        status: undefined
      },
      // 列信息
      columns: [
        { key: 0, label: `角色编号`, visible: true },
        { key: 1, label: `角色名称`, visible: true },
        { key: 2, label: `状态`, visible: true },
        { key: 3, label: `创建时间`, visible: true }
      ],
      // 表单校验
      rules: {
        
      }
    };
  },
  watch: {
   
  },
  created() {
    this.selectRole();
    getStatusApi().then(data=>{
      this.statusOptions = data.data;
    })
    getSexApi().then(data=>{
      this.sexOptions = data.data;
    });
  },
  methods: {
    //查询角色
    selectRole(){
      selectRoleApi(this.queryParams).then(data=>{
        this.roleList = data.data.returnDate;
        this.sum = data.data.paginationData.sum;
        this.loading = false;
      }).catch(()=>{
        this.roleList = null;
        this.sum = 0;
        this.loading = false;
      })
    },
    //查询菜单
     selectMenu(id){
      selectRoleMenuApi({
        "id": id
      }).then(data=>{
        this.menuList=  data.data;
        this.roleId = id;
        this.$nextTick(function(){
          this.initMenu();
        })
      }).catch(()=>{
      })
      this.loadingMenu = false;
    },handleSelect(row){
      this.title = "分配用户——"+ row.name;
      this.openUser = true;
      this.queryUser.id = row.id;
      this.selectUser();
      this.roleId = row.id;
      this.loadingUser = false;
    },
    //查询菜单
     selectUser(){
      selectUserRoleApi(this.queryUser).then(data=>{
      this.userList = data.data.returnDate;
      this.sumUser = data.data.paginationData.sum;
      }).catch(()=>{
        this.userList = null;
        this.sumUser = 0;
      })
      
    },
    switchUser () {
      if(this.queryUser.userType ==0){
        this.userButtonTilet1 = "已授权";
        this.userButtonTilet2 = "添加授权";
        this.userButtonTilet3 = "全部授权";
        this.queryUser.userType = 1;
      }else{
        this.userButtonTilet1 = "未授权";
        this.userButtonTilet2 = "取消授权";
        this.userButtonTilet3 = "全部取消";
        this.queryUser.userType = 0;
      }
      this.selectUser();
    },
    batchUser () {
      if(this.queryUser.userType ==0){
        this.userButtonTilet1 = "已授权";
        this.userButtonTilet2 = "添加授权";
        this.userButtonTilet3 = "全部授权";
        this.queryUser.userType = 1;
      }else{
        this.userButtonTilet1 = "未授权";
        this.userButtonTilet2 = "取消授权";
        this.userButtonTilet3 = "全部取消";
        this.queryUser.userType = 0;
      }
      this.selectUser();
    },
    allUser () {
      if(this.queryUser.userType ==0){
        this.userButtonTilet1 = "已授权";
        this.userButtonTilet2 = "添加授权";
        this.userButtonTilet3 = "全部授权";
        this.queryUser.userType = 1;
      }else{
        this.userButtonTilet1 = "未授权";
        this.userButtonTilet2 = "取消授权";
        this.userButtonTilet3 = "全部取消";
        this.queryUser.userType = 0;
      }
      this.selectUser();
    },
    /** 重置按钮操作 */
    resetQuery() {
      if (this.$refs["queryForm"]) {
		    this.$refs["queryForm"].resetFields();
	    }
      this.selectRole();
    },
     /** 重置按钮操作 */
    resetQueryUser() {
      if (this.$refs["queryFormUser"]) {
		    this.$refs["queryFormUser"].resetFields();
	    }
      this.selectUser();
    },
    // 角色状态修改
    statusChange(row) {
      let text = row.status === "0" ? "启用" : "停用";
      this.$confirm('确认要"' + text + '""' + row.name + '"角色吗?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(()=> {
          updateRoleStatusApi({
            "id": row.id,
            "status": row.status
          }).then(()=>{
            this.$message({
               type: 'success',
              message: '修改成功'
            });
          })
        }).catch(()=> {
          row.status = row.status === "0" ? "1" : "0";
        });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm('是否确认删除角色编号为"' + row.id + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(()=> {
          deleteRoleApi({
            "id": row.id
          }).then(data=>{
            this.selectRole();
            this.$message({
               type: 'success',
              message: '删除成功'
            });
          })
        })
    },
    /** 修改按钮操作 */
    handleMenu(row) {
      this.title = "分配菜单——"+row.name;
      this.openMenu = true;
      this.selectMenu(row.id);
    }, 
    /** 修改按钮操作 */
    handleCancel(row) {
      this.$confirm('是否确认修改用户编号为"' + row.id + '"的角色权限?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(()=> {
          cancelRoleUserApi({
            "userId": row.id,
             "id":this.roleId,
             "userType":this.queryUser.userType
          }).then(data=>{
            if(data.code == "200"){
              this.$message({
               type: 'success',
              message: '操作成功'
             });
              this.selectUser();
            }
          })
        })
    },
    /** 角色修改 */
    toUpdate() {
      let selection = this.$refs.menuRef.selection;
      let menuIds = ""; 
      selection.forEach(element => {
        menuIds += ","+element.id;
      });
      if (menuIds.substr(0,1) == ',')  menuIds = menuIds.substr(1);
      updateRoleMenuApi({
        "menuIds": menuIds,
        "id":this.roleId
      }).then(data=>{
        this.openMenu = false;
      })
      
    }, 
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      selectRoleApi({
        "id": row.id,
        "page":1,
        "number":1
      }).then(data=>{
        this.title = "修改角色";
        this.form.id = data.data.returnDate[0].id;
        this.form.name = data.data.returnDate[0].name;
        this.form.status = data.data.returnDate[0].status;
        this.open = true;
        this.selectRole();
      })
    }, // 表单重置
    reset() {
      this.form = {
        id: undefined,
        name: undefined,
        status: undefined,
      };
       if (this.$refs["form"]) {
		    this.$refs["form"].resetFields();
	    }
    },
    clickAdd(){
      this.title = "添加角色"
      this.open = true;
      this.reset();
    },
     /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            updateRoleApi(this.form).then(data=>{
              this.open = false;
              this.selectRole();
              this.reset();
              this.$message({
                type: 'success',
                message: '修改成功'
              });
            })
          } else {
            addRoleApi(this.form).then(data=>{
              this.open = false;
              this.selectRole();
              this.reset();
              this.$message({
                type: 'success',
                message: '添加成功'
              });
            })
          }
        }
      });
    }, // 取消按钮
    cancel() {
      this.open = false;
    }, // 取消按钮
    cancelMenu() {
      this.openMenu = false;
    },
    //选择行改变子节点
    rowSelect_children(menu,data){
      for(let i=0;i<menu.length;i++){
        this.$refs.menuRef.toggleRowSelection(menu[i],data);
        if(menu[i].children){
            this.rowSelect_children(menu[i].children,data);
        }
        menu[i].checked = data;
      }
    },
    rowSelect_parent(menu,parentId){
      if(parentId == '0'){
        return false;
      }
      for(let i=0;i<menu.length;i++){
        if(menu[i].id == parentId){
          this.$refs.menuRef.toggleRowSelection(menu[i],true);
          menu[i].checked = true;
          return true;
        }
        if(menu[i].children){
            if(this.rowSelect_parent(menu[i].children,parentId)){
               this.$refs.menuRef.toggleRowSelection(menu[i],true);
               menu[i].checked = true;
               return true;
            }
        }
      }
      return false;
    }
    ,
    //行选择
    rowSelect(selection, row) {
      if(row.children){
        if(row.checked){
          this.rowSelect_children(row.children,false);
          row.checked = false;
        }else{
          this.rowSelect_parent(this.menuList,row.parentId);
          this.rowSelect_children(row.children,true);
          row.checked = true;
        }
      }
      
    },
    //初始化也拥有菜单权限
    initChecked(menu){
      for(let i=0;i<menu.length;i++){
        if(menu[i].checked){
            this.$refs.menuRef.toggleRowSelection(menu[i],true);
            this.initChecked(menu[i].children);
        }
      }
    },
    //初始化角色
    initMenu(){
    this.initChecked(this.menuList);
    },
    //全选实际执行操作
    selectAll_children(menu){
      for(let i=0;i<menu.length;i++){
        this.$refs.menuRef.toggleRowSelection(menu[i],this.isSelectMenu);
        menu[i].checked = this.isSelectMenu;
        if(menu[i].children){
          this.selectAll_children(menu[i].children)
        }
      }
    },
    //点击全选框时的操作
    selectAll() {
      this.selectAll_children(this.menuList)
      this.isSelectMenu = !this.isSelectMenu;
    }
  }
};
</script>